// Initialize butotn with users's prefered color

var nick="";
var gh = (function() {

  return {
    onload: function () {
        getNickNameButton = document.querySelector('#getNickName');
        getNickNameButton.onclick = getNickName;
        setNickName();
        var tool = function () {
            var paperLoopNum = 0;
            var paperTempleArr = [
                '<div class="list-group-item list-group-item-success">{0}</div>',
                '<div class="list-group-item list-group-item-info">{0}</div>',
                '<div class="list-group-item list-group-item-warning">{0}</div>',
                '<div class="list-group-item list-group-item-danger">{0}</div>'
            ];
            return {
                paperDiv: function (val) {

                    var hl = paperTempleArr[paperLoopNum];
                    paperLoopNum++;
                    if (paperLoopNum >= paperTempleArr.length) { paperLoopNum = 0; }

                    return this.formart(hl, [val])
                },
                formart: function (str, arrVal) {

                    for (var i = 0; i < arrVal.length; i++) {
                        str = str.replace("{" + i + "}", arrVal[i]);
                    }
                    return str;
                }
            }
        };
        xia();
        function setNickName() {
            chrome.storage.local.get(['nickName'], function(result) {
                if (result.nickName!==undefined){
                    document.getElementById("getNickName").style.visibility="hidden";
                    document.getElementById("nickname").innerText="昵称："+result.nickName;
                }

            });
        }
        function xia() {
            qixia('GET', 'http://101.34.184.45:80/getMessage',
                false, qi);
        }
        function qixia(method, url, interactive, callback) {
            var xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.onload = requestComplete;
            xhr.send();
            function requestComplete() {
                // console.log('requestComplete', this.status, this.response);
                if ( ( this.status < 200 || this.status >=300 ) ) {

                } else {
                    callback(null, this.status, this.response);
                }
            }
        }
        function qi(error, status, response) {
            if (!error && status == 200) {
                var tl = new tool();
                var poem = JSON.parse(response);
                var i=poem.length-1;
                if(i>5){
                i=5;}
                for (i; i>=0; i--) {
                    showMsg("divShow", tl.paperDiv("【" + poem[i].split("-")[0] + "】：" + poem[i].split("-")[1]), true);

              }
            }
        }
        function getNickName() {
            qixia('GET', 'http://101.34.184.45:80/getNickName',
                false, getNickNameResponse);
        }
        function getNickNameResponse(error, status, response) {
            if (!error && status == 200) {
                nick=JSON.parse(response);
                chrome.storage.local.set({nickName:JSON.parse(response)}, function () {
                    document.getElementById("nickname").innerText="昵称："+JSON.parse(response);
                    document.getElementById("getNickName").style.visibility="hidden";

                });
            }
        }
        function showMsg(id, hl, isAppend) {
            if (!isAppend) { $("#" + id).html(hl); } else {
                $("#" + id).append(hl);
            }
        }
        $(function () {
            chrome.storage.local.get(['nickName'], function (result) {
                //初始化工具方法
                var tl = new tool();
                var wsUrl = "ws://101.34.184.45:88/webSocket";
                ws = new WebSocket(wsUrl);
                try {
                    ws.onopen = function () {
                        //showMsg("divShow", tl.paperDiv("连接服务器-成功"));
                    }

                    ws.onclose = function () {
                        if (ws) {
                            ws.close();
                            ws = null;
                        }
                        showMsg("divShow", tl.paperDiv("连接服务器-关闭"), true);
                    }

                    ws.onmessage = function (result) {

                        //console.log(result.data);
                        var data = JSON.parse(result.data);
                        $(data.UserMsgs).each(function (i, item) {
                            showMsg("divShow", tl.paperDiv("【" + item.UserName + "】：" + item.Msg), true);
                        });
                    }
                    ws.onerror = function () {
                        if (ws) {
                            ws.close();
                            ws = null;
                        }
                        showMsg("divShow", tl.paperDiv("连接服务器-关闭"), true);
                    }

                } catch (e) {

                    alert(e.message);
                }
                $("#btnSend").on("click", function () {
                    var tContentObj = $("#txtContent");
                    var tContent = $.trim(tContentObj.val()).replace("/[\n]/g", "");
                    var tUserName =result.nickName;
                    if (result.nickName===undefined&&nick!==undefined) {
                        tUserName=nick;
                    }
                    if (result.nickName===undefined&&nick===undefined){
                        alert("请选择昵称");
                        return;
                    }

                    if (tContent.length <= 0 || $.trim(tContent).length <= 0) {
                        alert("请输入发送内容!");
                        return;
                    }
                    if (ws == null) {
                        alert("连接失败，请F5刷新页面!");
                        return;
                    }

                    var request = tl.formart('{"UserName": "{0}", "DataType": "{1}", "Msg": "{2}" }',
                        [tUserName, "send", tContent]);
                    ws.send(request);
                    tContentObj.val("");
                    tContentObj.val($.trim(tContentObj.val()).replace("/[\n]/g", ""));
                });
                $("#txtContent").on("keydown", function (event) {
                    if (event.keyCode == 13) {
                        $("#btnSend").trigger("click");
                    }
                });
            })


        });

   }
  };




})();



window.onload = gh.onload;